package com.harunasan.carrental.api.serve.oss.controller;

import com.harunasan.carrental.api.serve.oss.service.FileService;
import com.harunasan.carrental.common.api.CommonResult;
import com.harunasan.carrental.common.api.ResultCode;
import com.harunasan.carrental.common.exception.OperationException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author LiangYi
 * @since 2022/2/28 00:13
 */
@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public CommonResult<String> upload(
            @ApiParam(value= "文件", required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "模块", required = true)
            @RequestParam("module") String module){

        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String url = fileService.upload(inputStream, module, originalFilename);
            return CommonResult.success(url);
        } catch (IOException e) {
            throw new OperationException(ResultCode.UPLOAD_FILE_ERROR.getMessage());
        }
    }

    @ApiOperation("删除oss文件")
    @DeleteMapping("/remove")
    public  CommonResult<String> remove(
            @ApiParam(value = "要删除的文件", required = true)
            @RequestParam("url") String url){
        fileService.removeFile(url);
        return  CommonResult.success("删除成功");
    }
}
